package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"struggle/dao/mysql"
	"struggle/logic"
)

type UserController struct{}

var DefaultUserController = &UserController{}

// RegisterRoute 管理 ImageController 路由
func (u UserController) RegisterRoute(r *gin.Engine) {
	//  个人用户 路由组
	api := r.Group("/api")
	{
		api.GET("/u", u.info)
		api.GET("/u/p", u.userArticleList)
		api.GET("/u/q", u.userQuestionList)
		api.GET("/u/a", u.userAnswerList)
	}
}

// 用户个人主页
func (u UserController) info(c *gin.Context) {
	sn, err := getIDFromQuery(c, "user_id")
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	// 获取用户个人信息
	user, err := mysql.GetUserByID(strconv.Itoa(int(sn)))
	if err != nil {
		zap.L().Error("get user info failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 获取用户统计表
	userCount, err := logic.DefaultUser.FindUserCount(user.UserSn)
	if err != nil {
		zap.L().Error("get user count info failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 构造返回数据
	data := map[string]interface{}{
		"user":       user,
		"user_count": userCount,
		"is_me":      false,
	}
	// 获取当前登录用户
	userSn, err := getCurrentUserSn(c)
	if err == nil && userSn == user.UserSn {
		data["is_me"] = true
	}

	ResponseSuccess(c, data)
	return
}

// 用户个人文章列表
func (u UserController) userArticleList(c *gin.Context) {
	offset, limit := getOffsetAndLimit(c)
	sn, err := getIDFromQuery(c, "user_id")
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	// 获取个人文章列表
	articles, err := logic.DefaultArticle.FindUserArticle(sn, offset, limit)
	if err != nil {
		zap.L().Error("get user articles info failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 构造返回数据
	data := map[string]interface{}{
		"articles": articles,
		"user_id":  sn,
	}
	ResponseSuccess(c, data)
	return
}

// 个人用户问题列表
func (u UserController) userQuestionList(c *gin.Context) {
	offset, limit := getOffsetAndLimit(c)
	sn, err := getIDFromQuery(c, "user_id")
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	// 获取个人用户问题列表
	questions, err := logic.GetUserQuestionList(sn, offset, limit)
	if err != nil {
		zap.L().Error("get user questions info failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 构造返回数据
	data := map[string]interface{}{
		"questions": questions,
		"user_id":   sn,
	}
	ResponseSuccess(c, data)
	return
}

// 个人用户回答列表
func (u UserController) userAnswerList(c *gin.Context) {
	offset, limit := getOffsetAndLimit(c)
	sn, err := getIDFromQuery(c, "user_id")
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	// 获取个人用户回答列表
	answers, err := logic.GetUserAnswerList(sn, offset, limit)
	if err != nil {
		zap.L().Error("get user answers info failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 构造返回数据
	data := map[string]interface{}{
		"answers": answers,
		"user_id": sn,
	}
	ResponseSuccess(c, data)
	return
}
